<template>
  <div class="app-container">
    <!-- 筛选表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="130px">
      <el-form-item label="预约人姓名" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入预约人姓名"
            clearable
            @keyup.enter="handleQuery"
            style="width: 250px;"
        />
      </el-form-item>
      <el-form-item label="预约人手机号" prop="mobile">
        <el-input
            v-model="queryParams.mobile"
            placeholder="请输入预约人手机号"
            clearable
            @keyup.enter="handleQuery"
            style="width: 250px;"
        />
      </el-form-item>
      <el-form-item label="预约状态" prop="status">
        <el-select
            v-model="queryParams.status"
            placeholder="请选择预约状态"
            clearable
            @change="handleQuery"
            style="width: 250px"
        >
          <el-option label="待上门" value="0"></el-option>
          <el-option label="已完成" value="1"></el-option>
          <el-option label="已取消" value="2"></el-option>
          <el-option label="已过期" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="预约时间" style="width: 380px">
        <el-date-picker
            v-model="daterangeAppointmentTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 250px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery" style="margin-left: 35px">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 预约类型切换 -->
    <div class="tab-group">
      <el-radio-group v-model="activeTab" @change="handleTabChange" size="medium">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button label="0">参观预约</el-radio-button>
        <el-radio-button label="1">探访预约</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="filteredAppointmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- 序号列修改：按1-n正序排列（使用当前页索引+1） -->
      <el-table-column label="序号" align="center" width="50">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="预约类型" align="center" prop="appointmentType" />
      <el-table-column label="预约人姓名" align="center" prop="name" />
      <el-table-column label="预约人手机号" align="center" prop="mobile" />
      <el-table-column label="老人姓名" align="center" prop="elderName" />
      <el-table-column label="预约时间" align="center" prop="appointmentTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.appointmentTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="status">
        <template #default="scope">
          <el-tag
              :type="getStatusTagType(scope.row.status)"
              effect="plain"
          >{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
              type="text"
              :disabled="isToHospitalDisabled(scope.row.status)"
              @click="handleToHospital(scope.row)"
          >到院</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 新增/修改弹窗：禁用手动选择“已过期” -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="appointmentRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="预约类型" prop="appointmentType">
          <el-radio-group v-model="form.appointmentType">
            <el-radio-button label="0">参观预约</el-radio-button>
            <el-radio-button label="1">探访预约</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="预约人姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入预约人姓名" />
        </el-form-item>
        <el-form-item label="预约人手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入预约人手机号" />
        </el-form-item>
        <el-form-item label="老人姓名" prop="elderName" :required="form.appointmentType === '1'">
          <el-input v-model="form.elderName" placeholder="请输入老人姓名" />
        </el-form-item>
        <el-form-item label="老人ID" prop="elderId" :required="form.appointmentType === '1'">
          <el-input v-model="form.elderId" placeholder="请输入老人ID" />
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker
              v-model="form.appointmentTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择预约时间"
              clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="预约状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择预约状态">
            <el-option label="待上门" value="0"></el-option>
            <el-option label="已完成" value="1"></el-option>
            <el-option label="已取消" value="2"></el-option>
            <el-option label="已过期" value="3" disabled></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Appointment">
import {
  listAppointment,
  getAppointment,
  delAppointment,
  addAppointment,
  updateAppointment
} from "@/api/appointment/appointment"
import {addVisit} from "@/api/visit/visit"
import {reactive, ref, computed, nextTick, onMounted} from 'vue'

const {proxy} = getCurrentInstance()

// 状态管理
const rawAppointmentList = ref([])
const appointmentList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const total = ref(0)
const title = ref("")
const daterangeAppointmentTime = ref([])
const activeTab = ref("all")
const currentAppointmentId = ref(null)
const currentAppointmentData = ref({})

// 过滤后的表格数据
const filteredAppointmentList = computed(() => {
  log('[filteredAppointmentList] 开始过滤数据，当前activeTab:', activeTab.value)
  const result = activeTab.value === "all"
      ? appointmentList.value
      : appointmentList.value.filter(item => item.appointmentTypeCode === activeTab.value)
  log('[filteredAppointmentList] 过滤后的数据量:', result.length)
  return result
})

// 表单与查询参数
const data = reactive({
  form: {
    id: null,
    appointmentType: null,
    name: null,
    mobile: null,
    elderName: null,
    elderId: null,
    appointmentTime: null,
    status: null,
    extend1: null,
    createdAt: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    mobile: null,
    status: null,
    appointmentType: null,
    params: {}
  },
  rules: {
    appointmentType: [{required: true, message: '请选择预约类型', trigger: 'change'}],
    name: [{required: true, message: '请输入预约人姓名', trigger: 'blur'}],
    mobile: [
      {required: true, message: '请输入预约人手机号', trigger: 'blur'},
      {pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur'}
    ],
    elderName: [
      {required: (form) => form.appointmentType === '1', message: '请输入老人姓名', trigger: 'blur'}
    ],
    elderId: [
      {required: (form) => form.appointmentType === '1', message: '请输入老人ID', trigger: 'blur'}
    ],
    appointmentTime: [{required: true, message: '请选择预约时间', trigger: 'change'}],
    status: [{required: true, message: '请选择预约状态', trigger: 'change'}]
  }
})

const {queryParams, form, rules} = toRefs(data)

// 调试日志函数（增加时间戳）
const log = (message, data = null) => {
  const timestamp = new Date().toLocaleTimeString()
  console.log(`[${timestamp}] [Appointment Debug] ${message}`, data !== undefined ? data : '')
}

// -------------------------- 核心功能：刷新页面检查过期预约 --------------------------
const checkExpiredOnRefresh = async () => {
  log('[checkExpiredOnRefresh] 开始执行过期预约检查')
  const now = new Date()
  const currentTimeStamp = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()
  log('[checkExpiredOnRefresh] 当前时间戳(当天0点):', currentTimeStamp, '对应日期:', new Date(currentTimeStamp).toLocaleDateString())

  const expiredList = rawAppointmentList.value.filter(item => {
    const isPending = item.status === 0 || item.status === '0'
    log(`[checkExpiredOnRefresh] 检查预约ID:${item.id}，状态:${item.status}，是否待上门:${isPending}`)

    if (!isPending) return false

    const appointmentDate = new Date(item.appointmentTime)
    const appointmentTimeStamp = new Date(appointmentDate.getFullYear(), appointmentDate.getMonth(), appointmentDate.getDate()).getTime()
    log(`[checkExpiredOnRefresh] 预约ID:${item.id}，预约时间:${item.appointmentTime}，对应时间戳:${appointmentTimeStamp}`)

    const isExpired = currentTimeStamp > appointmentTimeStamp
    log(`[checkExpiredOnRefresh] 预约ID:${item.id}，是否过期:${isExpired}`)
    return isExpired
  })

  log('[checkExpiredOnRefresh] 筛选出的过期预约数量:', expiredList.length, '过期ID列表:', expiredList.map(item => item.id))

  if (expiredList.length === 0) {
    log('[checkExpiredOnRefresh] 无过期预约，结束检查')
    return
  }

  appointmentList.value = appointmentList.value.map(item => {
    const isExpired = expiredList.some(exp => exp.id === item.id)
    const result = isExpired
        ? {...item, status: '已过期', statusCode: '3'}
        : item
    if (isExpired) log(`[checkExpiredOnRefresh] 前端更新预约ID:${item.id}状态为已过期`)
    return result
  })

  try {
    const updateDataList = expiredList.map(item => ({id: item.id, status: 3}))
    log('[checkExpiredOnRefresh] 准备批量更新过期预约，更新数据:', updateDataList)

    await Promise.all(updateDataList.map(data => updateAppointment(data)))
    proxy.$modal.msgSuccess(`刷新成功！自动更新${expiredList.length}条过期预约`)
    log(`[checkExpiredOnRefresh] 成功更新${expiredList.length}条过期预约`)
  } catch (error) {
    proxy.$modal.msgError(`部分预约更新失败：${error.message}`)
    console.error('[checkExpiredOnRefresh] 更新过期预约失败:', error)
    getList()
  }
}

// -------------------------- 列表查询：加载后触发刷新检查 --------------------------
function getList() {
  log('[getList] 开始获取预约列表，当前查询参数:', {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    name: queryParams.value.name,
    mobile: queryParams.value.mobile,
    status: queryParams.value.status,
    timeRange: daterangeAppointmentTime.value
  })

  loading.value = true
  queryParams.value.params = {}

  if (daterangeAppointmentTime.value && daterangeAppointmentTime.value.length) {
    queryParams.value.params.beginAppointmentTime = daterangeAppointmentTime.value[0]
    queryParams.value.params.endAppointmentTime = daterangeAppointmentTime.value[1]
    log('[getList] 设置时间范围参数:', {
      begin: queryParams.value.params.beginAppointmentTime,
      end: queryParams.value.params.endAppointmentTime
    })
  }

  listAppointment(queryParams.value).then(response => {
    log('[getList] 成功获取预约列表，原始响应数据:', {
      total: response.total,
      rowsCount: response.rows.length
    })

    rawAppointmentList.value = response.rows
    total.value = response.total

    appointmentList.value = rawAppointmentList.value.map(row => {
      const typeText = row.appointmentType === 0 || row.appointmentType === '0'
          ? '参观预约'
          : row.appointmentType === 1 || row.appointmentType === '1'
              ? '探访预约'
              : '未知类型'

      const statusMap = {0: '待上门', 1: '已完成', 2: '已取消', 3: '已过期'}
      const statusText = statusMap[row.status] || '未知状态'

      const formattedRow = {
        ...row,
        appointmentType: typeText,
        appointmentTypeCode: String(row.appointmentType),
        status: statusText,
        statusCode: String(row.status)
      }
      log(`[getList] 格式化预约数据ID:${row.id}，处理后数据:`, {
        appointmentType: formattedRow.appointmentType,
        typeCode: formattedRow.appointmentTypeCode,
        status: formattedRow.status,
        elderId: formattedRow.elderId
      })
      return formattedRow
    })

    loading.value = false
    log('[getList] 列表加载完成，触发过期检查')
    checkExpiredOnRefresh()
  }).catch(error => {
    console.error('[getList] 获取预约数据失败:', error)
    loading.value = false
  })
}

// -------------------------- 到院功能实现 --------------------------
const isToHospitalDisabled = (status) => {
  const disabled = ['已完成', '已取消', '已过期'].includes(status)
  log(`[isToHospitalDisabled] 状态:${status}，是否禁用到院按钮:${disabled}`)
  return disabled
}

const handleToHospital = (row) => {
  log('[handleToHospital] 触发到院操作，当前行数据:', {
    id: row.id,
    name: row.name,
    appointmentType: row.appointmentType,
    typeCode: row.appointmentTypeCode, // 记录预约类型编码
    elderName: row.elderName,
    elderId: row.elderId,
    status: row.status
  })

  // 仅探访预约（typeCode=1）需要校验老人ID，参观预约（typeCode=0）不需要
  if (row.appointmentTypeCode === '1' && !row.elderId) {
    log('[handleToHospital] 探访预约但老人ID为空，阻止操作')
    proxy.$modal.msgError("该探访预约缺少老人ID，无法完成到院登记")
    return
  }

  currentAppointmentId.value = row.id
  currentAppointmentData.value = row

  const currentTime = new Date()
  const formattedTime = parseTime(currentTime, '{y}-{m}-{d} {h}:{i}:{s}')
  log('[handleToHospital] 当前时间:', formattedTime)

  proxy.$modal.confirm(`是否以当前时间（${formattedTime}）作为到访时间？`).then(() => {
    log('[handleToHospital] 用户确认使用当前时间作为到访时间')
    confirmToHospital(currentTime)
  }).catch(() => {
    log('[handleToHospital] 用户取消到院操作')
  })
}

const confirmToHospital = (visitTime) => {
  log('[confirmToHospital] 开始执行确认到院流程，到访时间:', visitTime)
  log('[confirmToHospital] 当前预约ID:', currentAppointmentId.value)
  log('[confirmToHospital] 当前预约数据:', {
    ...currentAppointmentData.value,
    typeCode: currentAppointmentData.value.appointmentTypeCode
  })

  // 更新预约状态
  updateAppointment({
    id: currentAppointmentId.value,
    status: 1
  }).then(updateRes => {
    log('[confirmToHospital] 预约状态更新成功，响应:', updateRes)

    // 构造来访登记数据：仅探访预约传递老人ID
    const visitData = {
      visitorName: currentAppointmentData.value.name,
      phone: currentAppointmentData.value.mobile,
      visitTime: parseTime(visitTime, '{y}-{m}-{d} {h}:{i}:{s}'),
      visitType: currentAppointmentData.value.appointmentTypeCode,
      createTime: parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
    }

    // 探访预约（typeCode=1）添加老人ID，参观预约（typeCode=0）不添加
    if (currentAppointmentData.value.appointmentTypeCode === '1') {
      visitData.elderlyId = currentAppointmentData.value.elderId
      log('[confirmToHospital] 探访预约，添加老人ID到来访数据:', visitData.elderlyId)
    } else {
      log('[confirmToHospital] 参观预约，不传递老人ID')
    }

    log('[confirmToHospital] 最终提交的来访登记数据:', visitData)

    // 提交来访登记
    addVisit(visitData).then(visitRes => {
      log('[confirmToHospital] 来访登记提交成功，响应:', visitRes)
      proxy.$modal.msgSuccess("到院操作成功，已生成来访登记")
      getList()
    }).catch(visitError => {
      log('[confirmToHospital] 来访登记提交失败:', visitError)
      proxy.$modal.msgError(`提交来访登记失败：${visitError.message || '未知错误'}`)
    })
  }).catch(updateError => {
    log('[confirmToHospital] 预约状态更新失败:', updateError)
    proxy.$modal.msgError(`更新预约状态失败：${updateError.message || '未知错误'}`)
  })
}

// 时间格式化
const parseTime = (time, format = '{y}-{m}-{d} {h}:{i}:{s}') => {
  if (!time) {
    log('[parseTime] 输入时间为空，返回空字符串')
    return ''
  }
  const date = new Date(time)
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds()
  }
  const result = format.replace(/{([ymdhsi])+}/g, (result, key) => {
    const value = formatObj[key]
    return value.toString().padStart(2, '0')
  })
  log(`[parseTime] 格式化时间:${time} → ${result}`)
  return result
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    '待上门': 'success',
    '已完成': 'success',
    '已取消': 'warning',
    '已过期': 'danger'
  }
  const type = typeMap[status] || ''
  log(`[getStatusTagType] 状态:${status} → 标签类型:${type}`)
  return type
}

// 表单提交
function submitForm() {
  log('[submitForm] 开始表单提交，当前表单数据:', form.value)

  proxy.$refs["appointmentRef"].validate(valid => {
    if (valid) {
      log('[submitForm] 表单验证通过，准备提交')
      const submitData = {
        ...form.value,
        appointmentType: Number(form.value.appointmentType),
        status: Number(form.value.status)
      }
      log('[submitForm] 处理后的提交数据:', submitData)

      const apiFn = form.value.id ? updateAppointment : addAppointment
      const operation = form.value.id ? '修改' : '新增'

      apiFn(submitData).then(response => {
        log(`[submitForm] ${operation}预约成功，响应:`, response)
        proxy.$modal.msgSuccess(`${operation}成功`)
        open.value = false
        getList()
      }).catch(error => {
        log(`[submitForm] ${operation}预约失败:`, error)
        proxy.$modal.msgError(`${operation}失败：${error.message || '未知错误'}`)
      })
    } else {
      log('[submitForm] 表单验证失败')
    }
  })
}

// 其他函数
function cancel() {
  log('[cancel] 取消操作，关闭弹窗')
  open.value = false
  reset()
}

function reset() {
  log('[reset] 重置表单数据')
  form.value = {
    id: null,
    appointmentType: null,
    name: null,
    mobile: null,
    elderName: null,
    elderId: null,
    appointmentTime: null,
    status: null,
    extend1: null,
    createdAt: null
  }
  proxy.resetForm("appointmentRef")
}

function handleQuery() {
  log('[handleQuery] 执行查询操作')
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  log('[resetQuery] 重置查询参数')
  queryParams.value.name = null
  queryParams.value.mobile = null
  daterangeAppointmentTime.value = []
  queryParams.value.status = null
  queryParams.value.appointmentType = null
  activeTab.value = "all"
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  log('[handleSelectionChange] 选择项变化，选中ID列表:', ids.value)
}

function handleAdd() {
  log('[handleAdd] 触发新增预约操作')
  reset()
  open.value = true
  title.value = "添加预约登记"
}

function handleUpdate(row) {
  log('[handleUpdate] 触发修改预约操作，选中行数据:', row)
  reset()
  const _id = row.id || ids.value
  log('[handleUpdate] 准备获取预约详情，ID:', _id)

  getAppointment(_id).then(response => {
    log('[handleUpdate] 获取预约详情成功，响应数据:', response.data)
    form.value = {
      ...response.data,
      appointmentType: String(response.data.appointmentType),
      status: String(response.data.status),
      elderId: response.data.elderId
    }
    open.value = true
    title.value = "修改预约登记"
  }).catch(error => {
    log('[handleUpdate] 获取预约详情失败:', error)
    proxy.$modal.msgError('获取预约详情失败')
  })
}

function handleDelete(row) {
  const _ids = row.id || ids.value
  log('[handleDelete] 触发删除操作，目标ID:', _ids)

  proxy.$modal.confirm(`是否确认删除预约登记编号为"${_ids}"的数据？`).then(() => {
    log('[handleDelete] 用户确认删除')
    return delAppointment(_ids)
  }).then(response => {
    log('[handleDelete] 删除成功，响应:', response)
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(error => {
    if (error !== 'cancel') { // 排除用户取消的情况
      log('[handleDelete] 删除失败:', error)
      proxy.$modal.msgError('删除失败')
    } else {
      log('[handleDelete] 用户取消删除')
    }
  })
}

function handleTabChange() {
  log('[handleTabChange] 标签切换，当前标签:', activeTab.value)
  queryParams.value.appointmentType = activeTab.value === "all" ? null : activeTab.value
  handleQuery()
}

// 初始化
onMounted(() => {
  log('[onMounted] 组件挂载完成，开始初始化')
  getList()
})
</script>

<style scoped>
.tab-group {
  margin: 15px 0;
}

:deep(.el-radio-button__inner) {
  border-radius: 4px 4px 0 0;
}

:deep(.el-radio-button.is-active .el-radio-button__inner) {
  background-color: #409eff;
  color: #fff;
  border-color: #409eff;
}

:deep(.el-tag--success) {
  background-color: #f0f9eb;
  color: #67c23a;
  border-color: #e1f3d8;
}

:deep(.el-tag--warning) {
  background-color: #fdf6ec;
  color: #e6a23c;
  border-color: #faecd8;
}

:deep(.el-tag--danger) {
  background-color: #fef0f0;
  color: #f56c6c;
  border-color: #fde2e2;
}
</style>